<route lang="json5">
{
  meta: {
    auth: true,
    label: '角色管理',
  },
}
</route>

<template>
  <div class="h-full flex flex-col">
    <div class="flex items-center overflow-x-scroll">
      <a-form :model="filterInfo" layout="inline">
        <a-form-item field="name" label="角色名称">
          <a-input v-model="filterInfo.name" placeholder="please enter 角色名称" />
        </a-form-item>
      </a-form>
      <a-button @click="handleEditInfo({})" status="warning" class="mr-2">添加角色</a-button>
      <a-button @click="getData" :loading="inLoading">刷新</a-button>
    </div>
    <use-n-progress :inanimate="inDebounce" />
    <a-table
      row-key="id"
      class="!h-0 flex-1"
      :scroll="{ y: '100%', x: '100%' }"
      :pagination="pagination"
      :data="dataList"
      :loading="inLoading"
      :columns="[
        { title: '角色名称', dataIndex: 'name', width: 170 },
        { title: '状态', slotName: 'status', width: 80 },
        { title: '备注', dataIndex: 'remark', width: 200 },
        { title: '操作', slotName: 'tools', width: 170, fixed: 'right', align: 'left' },
      ]"
    >
      <template #status="{ record }">
        <common-status-tag :value="record.status" />
      </template>
      <template #tools="{ record }">
        <a-button class="mr-2" title="编辑信息" @click="handleEditInfo(record)">
          <template #icon>
            <Icon icon="ant-design:edit-twotone" />
          </template>
        </a-button>
        <a-button class="mr-2" title="编辑权限" @click="handleEditAuth(record)">
          <template #icon>
            <Icon icon="ant-design:edit-twotone" />
          </template>
        </a-button>
        <a-button @click="handleDelete([record.id])" class="mr-2" title="删除">
          <template #icon>
            <Icon icon="ant-design:delete-twotone" />
          </template>
        </a-button>
      </template>
    </a-table>

    <!-- 编辑/新增角色 -->
    <a-modal width="auto" v-model:visible="visible" title-align="start" draggable :on-before-ok="handleSubmit">
      <template #title>{{ formData.id ? '编辑' : '新增' }}</template>
      <a-form ref="editFormRef" auto-label-width :model="formData" :style="{ width: '480px' }">
        <a-form-item field="name" label="名称" :rules="{ required: true, message: '名称必填！' }">
          <a-input v-model="formData.name" />
        </a-form-item>
        <a-form-item field="status" label="启用">
          <a-switch
            v-model="formData.status"
            type="round"
            checked-text="启用"
            unchecked-text="隐藏"
            :checked-value="1"
            :unchecked-value="0"
          />
        </a-form-item>
        <a-form-item field="sort" label="排序">
          <a-input-number v-model="formData.sort" />
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea
            v-model="formData.remark"
            :auto-size="{
              minRows: 2,
              maxRows: 5,
            }"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="tsx" setup>
import { getAuthRole, getAuthList, type IGetAuthList } from 'api/test1'
import { cloneDeep } from 'lodash-es'

const DEFAULT_FORM = {
  id: '',
  name: '',
  status: undefined,
  sort: undefined,
  remark: '',
}
const DefaultFilter = {
  name: '',
}
const visible = ref()
const editFormRef = ref()
const formData = reactive(cloneDeep(DEFAULT_FORM))

const { dataList, filterInfo, inDebounce, pagination, inLoading, getData } = useGetData<any, typeof DefaultFilter>(
  getAuthRole,
  DefaultFilter,
  {
    usePagination: false,
  },
)

async function handleDelete(ids: string[]) {
  await useConfirm()
  await getAuthRole() // 模拟删除
  await getData()
}

async function handleEditInfo(row: any = {}) {
  Object.assign(formData, DEFAULT_FORM, row)
  editFormRef.value?.clearValidate()
  await nextTick()
  visible.value = true
}

async function handleSubmit() {
  const error = await editFormRef.value.validate()
  if (error) return false
  await getAuthRole()
}

// 编辑权限
async function handleEditAuth(row: any = {}) {
  const list = ref<IGetAuthList[]>([])
  await getAuthList().then((e) => {
    list.value = e.list
  })
  Modal.open({
    title: `编辑权限（${row.name}）`,
    content: () => (
      <>
        <div class=' whitespace-pre max-h-[60vh] overflow-y-auto'>
          {list.value.map(({ menuInfo, toolsList }) => (
            <a-card title={menuInfo.name}>
              {{
                extra: () => (
                  <>
                    <a-button
                      onClick={() => {
                        toolsList.map((e) => (e.has = true))
                      }}
                      size='mini'
                    >
                      全选
                    </a-button>
                    <a-button
                      onClick={() => {
                        toolsList.map((e) => (e.has = false))
                      }}
                      size='mini'
                    >
                      全不选
                    </a-button>
                  </>
                ),
                default: () => (
                  <div class='flex flex-wrap gap-2'>
                    {toolsList.map((tool) => (
                      <a-checkbox v-model={tool.has}>{tool.name}</a-checkbox>
                    ))}
                  </div>
                ),
              }}
            </a-card>
          ))}
        </div>
      </>
    ),
    async onBeforeOk(done) {
      await getAuthList()
      done(true)
    },
  })
}
</script>
